package cn.com.flever.utils;

import cn.com.flever.config.SysConfig;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class EncryptionUtils {

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 默认公钥
     */
    private static final String DEFAULT_PUBLIC_KEY="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClbOPpQotqE4PRE3uLudAB9kTOOLXkSnnXEo0c0u+pe29VZsqO7mx7Zl4oX6o/7rvfRw3ErXylphebdVLkRODCLImdcWy0IgrNWOaPUxs81aUc4ZfVpHxXfsppda0MYB9a9T6j88XjO6+HcpOrZb0O5D2V2h5bYMG5VsqDAe9HXwIDAQAB";

    /**
     * 默认私钥
     */
    private static final String DEFAULT_PRIVATE_KEY="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKVs4+lCi2oTg9ETe4u50AH2RM44teRKedcSjRzS76l7b1Vmyo7ubHtmXihfqj/uu99HDcStfKWmF5t1UuRE4MIsiZ1xbLQiCs1Y5o9TGzzVpRzhl9WkfFd+yml1rQxgH1r1PqPzxeM7r4dyk6tlvQ7kPZXaHltgwblWyoMB70dfAgMBAAECgYEAnaQP6Hh+jJ5+Lh5nzHZMz6HUXcTTKPMD+r119fLZamPza6nh+6UfgdTCg6zue7BQHm0CpNtCfkSyGHYMgPVWTIqBWEwj+f+m7xZ9L5hO6yiJ7DN5rVBw+56c2d/kD8vz2sho2A8y4CUEre9GgoE/WXaJYaC6Oe6aS7wzVMj14CkCQQDdsNM+cXGAt+3tWoixBKh3F+ytvJeX+hSpVlWPhqiEQdCHmdspawYV6wSFeO9ay51IOSJ4ljuKL8C3r7FLihFzAkEAvwbihFr4HEFnTIHyJ/2msLvTGkIVypHcp03Uz6RknwhHYv/5hjZJTWC2FTqA2l2SEQKLQOuHTLmuhClFygLHZQJANt+0CjrOW4wriprkRtzeTkxPu1l5NJckUh4ao6IzSDl6QnZk90WUhgxcXCVpKdJIpj3uOGcHadcUHuOQQSB13QJAT2qfVYM0TxrpxSbo87NCT4tmki4TPSoy3+M9rC2eH3ejpgbhR+jdxKuGR4EQ/LeV+DhkiFLi5wTzBsLZ3sgU+QJAQTq2e9jFr2sJwEfqqtpH6PK4kq+qHZRbjD3xmEiQHeQaGOx06RKpi12ThBt7Qv4+AChaoyM67PXJ4zYaSWr+kg==";

    /**
     * 用户配置的私钥
     */
    private static String USER_PRIVATE_KEY= SysConfig.getConfiguration().getProperty("client.privateKey");

    /**
     * 用户配置的公钥
     */
    private static String USER_PUBLIC_KEY= SysConfig.getConfiguration().getProperty("client.publicKey");



    /**
     * 获取密钥对
     *
     * @return 密钥对
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(1024);
        return generator.generateKeyPair();
    }

    /**
     * 获取私钥
     *
     * @param privateKey 私钥字符串
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * RSA加密
     *
     * @param data 待加密数据
     * @param publicKey 公钥
     * @return
     */
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
        // 加密后的字符串
        return new String(Base64.encodeBase64String(encryptedData));
    }

    /**
     * RSA解密
     *
     * @param data 待解密数据
     * @param privateKey 私钥
     * @return
     */
    public static String decrypt(String data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密后的内容
        return new String(decryptedData, "UTF-8");
    }

    /**
     * 签名
     *
     * @param data 待签名数据
     * @param privateKey 私钥
     * @return 签名
     */
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(key);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }

    /**
     * 验签
     *
     * @param srcData 原始字符串
     * @param publicKey 公钥
     * @param sign 签名
     * @return 是否验签通过
     */
    public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(key);
        signature.update(srcData.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }

    /**
     * 加密
     * @param data
     * @return
     */
    public static String encrypt(String data)
    {
        try
        {
            String publicKey= StringUtils.isEmpty(USER_PUBLIC_KEY)?DEFAULT_PUBLIC_KEY:USER_PUBLIC_KEY;
            String encryptData = encrypt(data, getPublicKey(publicKey));
            return encryptData;
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 解密
     * @param encryptData
     * @return
     */
    public static String decrypt(String encryptData)
    {
        try
        {
            String privateKey= StringUtils.isEmpty(USER_PRIVATE_KEY)?DEFAULT_PRIVATE_KEY:USER_PRIVATE_KEY;
            String data = decrypt(encryptData, getPrivateKey(privateKey));
            return data;
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return encryptData;
    }

    public static void main(String[] args) {
        try {
           /* // 生成密钥对
            KeyPair keyPair = getKeyPair();
            String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
            String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
            System.out.println("私钥:" + privateKey);
            System.out.println("公钥:" + publicKey);
            // RSA加密
            String data = "待加密的文字内容";
            String encryptData = encrypt(data, getPublicKey(publicKey));
            System.out.println("加密后内容:" + encryptData);
            // RSA解密
            String tmp="W++2UHIrapE3Vu5nmIqYist+rk02KOmSmn2nwKksKCp+9ewtDKxPRxBD2FAo6IsK0CGWX+a2x24dG0ZSi7BoH+3ukgv/ZSnTa9Z+wex2vL7Moovp4pzBaW29vQjJAB4SPpM1gwz/rE6hk6zWaTt4TfxYnNEi2UkSnjM62+L4HWs=";
            byte[] bytes = Base64.decodeBase64(tmp);
            String decryptData = decrypt(new String(bytes), getPrivateKey(privateKey));
            System.out.println("解密后内容:" + decryptData);*/

            String tmp="C+JdRCk6AwfcZujEhO7VS+yLWsSeAGwCeW/Gdac3dzumaMAUqCKw6KXbpoYCXCc5TYnAqsRkB9BJs/Zkpf7FGckPDA+3bJwMKyBoZMqkyo5A9805JoGDGm59F+uj2yYWEKYM65284yBxIYAtIX/uX9jq3oQ+nqemuha4mWo8q/w=";
            String tmpPrivateKey="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAI2lPadlMCtO4RbeRHymzEnzqwLPZw/qjFhZH0HCcvqQTYksGmVsR4wMvkVJAEnF0As1N8UC0hEpWy9X3xof6ez0e5J4BNe3YO3P5WJs+xg1ZQKw+GKW6mlyb7lkkVV/mw9ZIO/tGYoxGmXlYS1vunm7K2Wm0Rjl8Cut6dixe1LDAgMBAAECgYAjJJA7a/ubgyKNje/oDWo6Ht6a/+JOLJ9NfC8pHZlxWUQjeHHEIC1QLgk3H3mW1CFd5oJDuwNrhps9D8wmqyxaY0Z3RbKm1AIhMC5VLlwQkFYviJMKskKCN5sp7pUWt8EbU72OPozhTvAK1i3ruB4oT1DlA+BCmXvcoFX0jRm9gQJBAMwOK4TziORRYQN2e2FAjBrkPMfaIrZFS+oRE3Gha+Xb7fxbDE/6IP4Ph/CS4IAVEPBy7Mdr85VUbcm80gvB4TECQQCxs/V2iFNRH/fSjKtFJM5JIBsjNH3jlf5TcpZt4gmENhuOIf4gEJ0YUbATBdDnLX6/XaeW03EcfOm4TbJmRVYzAkEAwwqgSlpFdIbcheTQFasOv/18o0I7f6FI6Jgdz7UNXw4Sse2NHTzmIDFULH0XnRWFtW8EJ7FliEzFC9kxpA9TYQJAdPMFmbPQeXR7icLwOLonVPLfSUUTkMM3NL4WCE0ZjDx72AfBEmM8sDOamHpcaLiFUPYXBGk1aNVAj/36ado6BwJBAMIT8oxwaLtnAjWQKMKiFhuzU2LvQoydBeVFY+tA1Tw69oB39zkA9tX2iMechaH7j60mLM1z5tYUqIdgEZEYX48=";
            byte[] bytes = tmp.getBytes();
            String decryptData = decrypt(new String(bytes),getPrivateKey(tmpPrivateKey));
            System.out.println("解密后内容:" + decryptData);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("加解密异常");
        }
    }
}